package com.atguigu.daijia.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CiService;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @author 谢忠涵7
 */
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {
    @Autowired
    private TencentCloudProperties tencentCloudProperties;
    @Autowired
    private CiService ciService;

    /**
     *  上传资料
     */
    @Override
    public CosUploadVo uploadFile(MultipartFile file, String path) {
        //1.创建腾讯云存储的客户端
        COSClient client = this.getPrivateCOSClient();
        //2.创建存储桶(在控制台创建了)
        //3.编写存储规则
        //元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());
        //向存储桶中保存文件
        //文件后缀名
        String fileType = Objects.requireNonNull(file.getOriginalFilename())
                .substring(file.getOriginalFilename().lastIndexOf("."));

        String uploadPath = "/driver/" + path + "/"
                + UUID.randomUUID().toString().replaceAll("-", "")
                + fileType;
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate()
                                                    , uploadPath
                                                    , file.getInputStream()
                                                    , meta);
        } catch (IOException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        putObjectRequest.setStorageClass(StorageClass.Standard);
        //上传文件
        PutObjectResult putObjectResult = client.putObject(putObjectRequest);
        log.info(JSON.toJSONString(putObjectResult));
        //审核图片
        Boolean isAuditing = ciService.imageAuditing(uploadPath);
        if(!isAuditing) {
            client.deleteObject(tencentCloudProperties.getBucketPrivate(), uploadPath);
            throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }
        client.shutdown();
        //4.创建回显地址因为腾讯云的地址是私人访问的
        String echoPath = this.getEchoPath(uploadPath);
        //5.封装VO对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        cosUploadVo.setShowUrl(echoPath);
        //6.返回
        return cosUploadVo;
    }

    /**
     * 创建回显地址
     */
    @Override
    public String getEchoPath(String path) {
        if(!StringUtils.hasText(path)) {
            return "";
        }
        COSClient cosClient = getPrivateCOSClient();
        GeneratePresignedUrlRequest request =
                new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate()
                                               , path
                                               , HttpMethodName.GET);
        //设置临时URL有效期为15分钟
        Date expiration = new DateTime()
                             .plusMinutes(15)
                             .toDate();
        request.setExpiration(expiration);
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }

    /**
     * @description: 创建腾讯云存储的客户端
     * @author: xiaoxie
     * @date: 2024/10/24 21:42
     * @param: []
     * @return: com.qcloud.cos.COSClient
     **/
    private COSClient getPrivateCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(tencentCloudProperties.getRegion()));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        return new COSClient(cred, clientConfig);
    }
}
